#pragma once
#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>

#include "Comm.hpp"

// socket中常用的头文件
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

namespace Network
{
    // 设置默认的套接字描述符
    const static int defaultfd = -1;
    const int backlog = 5;

    enum // 错误码
    {
        SocketError = -1,
        BindError,
        ListenError
    };

    // 封装一个Socket类，用于创建、绑定、监听、连接、发送、接收等操作
    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;                                  // 创建套接字
        virtual void BindSocketOrDie(uint16_t port) = 0;                       // 绑定套接字
        virtual void ListenSocketOrDie(int backlog) = 0;                       // 监听套接字
        virtual int AcceptConnection(string *peerip, uint16_t *peerport) = 0;  // 接受连接
        virtual bool ConnectServer(string &serverip, uint16_t serverport) = 0; // 连接服务器
        virtual int GetSockfd() = 0;                                           // 获取套接字描述符
        virtual void SetSockfd(int sockfd) = 0;                                // 设置套接字描述符
        virtual void CloseSocket() = 0;                                        // 关闭套接字
        virtual bool Recv(string *buffer, int size) = 0;                       // 接收数据
        virtual void Send(string &send_str) = 0;                               // 发送数据
        virtual void ReUseAddr() = 0;                                          // 重用地址
        // TODO

    public:
        void BuildlistenSocketMethod(uint16_t port, int backlog)
        {
            CreateSocketOrDie();        // 创建套接字
            ReUseAddr();                // 重用地址
            BindSocketOrDie(port);      // 绑定套接字
            ListenSocketOrDie(backlog); // 监听套接字
        }
        bool BuildconnectSocketMethod(string &serverip, uint16_t serverport)
        {
            CreateSocketOrDie();                        // 创建套接字
            return ConnectServer(serverip, serverport); // 连接
        }

        void BuildNormalSocketMethod(int sockfd)
        {
            SetSockfd(sockfd);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = defaultfd) : _sockfd(sockfd)
        {
        }
        void CreateSocketOrDie() override
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0); // 创建套接字描述符
            if (_sockfd < 0)
            {
                exit(SocketError);
            }
            SetNonblock(_sockfd); // 将listensock设置成为非阻塞
        }
        void BindSocketOrDie(uint16_t port) override
        {
            struct sockaddr_in local;           // 创建套接字地址空间
            memset(&local, 0, sizeof(local));   // 清空地址空间
            local.sin_family = AF_INET;         // 设置ipv4地址族
            local.sin_port = htons(port);       // 设置端口号,htons()将主机字节序转换为网络字节序
            local.sin_addr.s_addr = INADDR_ANY; // 设置地址为0.0.0.0,这样可以接收来自任何地址的连接请求

            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local)); // 绑定套接字
            if (n < 0)
            {
                exit(BindError);
            }
        }
        void ListenSocketOrDie(int backlog) override
        {
            int n = ::listen(_sockfd, backlog); // 监听套接字
            if (n < 0)
            {
                exit(ListenError);
            }
        }
        int AcceptConnection(string *peerip, uint16_t *peerport) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len); // 接受连接,peer是客户端的地址信息
            if (newsockfd < 0)
                return -1;

            *peerip = inet_ntoa(peer.sin_addr); // 将网络字节序的IP地址转换为字符串形式
            *peerport = ntohs(peer.sin_port);   // 将网络字节序的端口号转换为主机字节序

            return newsockfd;
        }
        bool ConnectServer(string &serverip, uint16_t serverport) override
        {
            // serverip服务器的ip，serverport服务器的端口号
            struct sockaddr_in server; // 创建套接字地址空间
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(serverport);
            server.sin_addr.s_addr = inet_addr(serverip.c_str());

            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server)); // 用于连接到指定的套接字地址，即与远程服务器建立连接。
            if (n == 0)
                return true;
            else
                return false;
        }
        int GetSockfd() override
        {
            return _sockfd; // 获取套接字描述符
        }
        void SetSockfd(int sockfd) override
        {
            _sockfd = sockfd; // 设置套接字描述符
        }

        void CloseSocket() override
        {
            if (_sockfd > defaultfd)
                ::close(_sockfd); // 关闭套接字
        }
        bool Recv(string *buffer, int size) override
        {
            char inbuffer[size];
            size_t n = recv(_sockfd, inbuffer, size - 1, 0); // 接收数据
            if (n > 0)
            {
                inbuffer[n] = 0;
                *buffer += inbuffer;
                return true;
            }
            else if (n == 0)
            {
                return false;
            }
            else
                return false;
        }
        void Send(string &send_str) override
        {
            send(_sockfd, send_str.c_str(), send_str.size(), 0);
        }
        void ReUseAddr() override
        {
            int optval = 1;
            setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); // 地址复用
        }
        // TODO

    private:
        int _sockfd;
    };
}